package com.hmdp.mapper;

import com.hmdp.entity.SeckillVoucher;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * <p>
 * 秒杀优惠券表，与优惠券是一对一关系 Mapper 接口
 * </p>
 *
 * @author 虎哥
 * @since 2022-01-04
 */
public interface SeckillVoucherMapper extends BaseMapper<SeckillVoucher> {
    //TODO：乐观锁解决超卖问题，性能较高，但失败率也高，适合读多写少场景，而且会增加数据库压力。实际上是使用了数据库的锁机制。
//    @Update(value = "update tb_seckill_voucher set stock = stock-1 where voucher_id = #{id}")
//    @Update(value = "update tb_seckill_voucher set stock = stock-1 where voucher_id = #{id} and stock > #{stock}")
    @Update(value = "update tb_seckill_voucher set stock = stock-1 where voucher_id = #{id} and stock > 0")
    public boolean minusStcokOne(@Param("id") Long id);


    @Select(value = "select count(*) from tb_voucher_order where user_id = #{userId} and voucher_id = #{voucherId}")
    public Integer countByUserIdAndVoucherId(@Param("voucherId") Long voucherId, @Param("userId") Long userId);

    @Select("select * from tb_seckill_voucher")
    List<SeckillVoucher> queryAll();

    @Select("select  * from tb_seckill_voucher where id = #{id}")
    SeckillVoucher queryById(Long id);
}
